//
//  AppDelegate.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/8/19.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import GoogleSignIn
import SafariServices
import IQKeyboardManager
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow.init(frame: UIScreen.main.bounds)
        window?.backgroundColor = .white
        if APPUser.shared.isLogin {
//            window?.rootViewController = MainTabBarViewController()
            window?.rootViewController = AEAppDelegateTool.sharedInstance().getMainTabBarVC();
        } else {
            window?.rootViewController = MainNavigationViewController.init(rootViewController: LoginViewController(type: .login))
        }
        
        
        // 初始化
        AEAppDelegateTool.sharedInstance();
        // 设置网络请求的根地址
//        TYZNetworkConfig.shared().baseUrl = kBaseUrl;
//        [TYZNetworkConfig sharedConfig].baseUrl = kBaseUrl;
        
        window?.makeKeyAndVisible()
        
        // 微信
        WXApi.registerApp(APPConfig.wxkey)
        
        // facebook
        ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
        
        // google
        FirebaseApp.configure()
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        
        IQKeyboardManager.shared().isEnableAutoToolbar = false
        
        let entity = JPUSHRegisterEntity()
        entity.types = Int(JPAuthorizationOptions.alert.rawValue | JPAuthorizationOptions.badge.rawValue | JPAuthorizationOptions.sound.rawValue)
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        
        JPUSHService.setup(withOption: launchOptions, appKey: "cd0c04f781c887c17710db9a", channel: "", apsForProduction: false)
        JPUSHService.registrationIDCompletionHandler{_ ,_ in}
        JPUSHService.setDebugMode()
        
        if AppCache.shared.object(for: APPUserDefault.self).userSelectLanguage == nil {
            let currentLanguage = UIDevice.current.currentLanguage
            AppCache.shared.updateObject(for: APPUserDefault.self) {
                if currentLanguage.contains("zh-Hans") {
                    $0.userSelectLanguage = .chinese
                } else if currentLanguage.contains("vi") {
                    $0.userSelectLanguage = .vi
                } else if currentLanguage.contains("de") {
                    $0.userSelectLanguage = .de
                } else {
                    $0.userSelectLanguage = .english
                }
            }
        }
        
        return true
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        APPMessage.shared.add(UIApplication.shared.applicationIconBadgeNumber)
        UIApplication.shared.applicationIconBadgeNumber = 0
        JPUSHService.resetBadge()
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        var bgTask: UIBackgroundTaskIdentifier = .invalid
        bgTask = application.beginBackgroundTask(expirationHandler: {
            DispatchQueue.main.async {
                if bgTask != .invalid {
                    bgTask = .invalid
                }
            }
        })
        DispatchQueue.global(qos: .default).async {
            DispatchQueue.main.async {
                if bgTask != .invalid {
                    bgTask = .invalid
                }
            }
        }
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        if ApplicationDelegate.shared.application(app, open: url, options: options) {
            return true
        }
        if let sourceApplication = options[.sourceApplication] as? String,
            let annotation = options[.annotation],
            GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication, annotation: annotation) {
            return true
        }
        
        if WXApi.handleOpen(url, delegate: self) { return true }
        return true
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
    }
}

extension AppDelegate: JPUSHRegisterDelegate {
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        let options = Int(JPAuthorizationOptions.sound.rawValue)
        
        if let userInfo = notification?.request.content.userInfo,
            let type = userInfo["type"] as? String,
            type == "1" {
            APPMessage.shared.addOne()
        }
        completionHandler(options)
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        completionHandler()
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification!) {
        
    }
}

extension AppDelegate: WXApiDelegate {
    
    func onResp(_ resp: BaseResp) {
        if resp.errCode == 0,
            let authResp = resp as? SendAuthResp,
            let code = authResp.code {
            let userInfo = ["code": code]
            NotificationCenter.default.post(name: .weChatLoginSuccess, object: nil, userInfo: userInfo)
        } else {
            APPHud.shared.showError(status: "微信登录失败".localized)
        }
    }
    
}
